"""
GUI关键字模块
"""
import os
from datetime import datetime

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from GUI.driver import Driver
from utils.log import Logger
from selenium.webdriver.support.select import Select
from config.config import PIC_PATH
'''class Keywords:

    def __init__(self,browser):
        self.driver = getattr(webdriver,browser)()
        self.driver.maximize_window()
        self.driver.implicitly_wait(5)

    def open(self,*args):
        self.driver.get(args[0])

    def wait(self,*args):
        import time
        time.sleep(int(args[0]))

    # def locator(self,loc):
    #     try:
    #         element = self.webdriver.find_element(*loc)
    #     except Exception as e:
    #         pass
    #     return element
    def query_element(self, by, value):
        element = None
        try:
            element = self.driver.find_element(getattr(By, by), value)
        except Exception as e:
            pass
        return element

    # def input(self,loc,values):
    #     self.locator(loc).send_keys(values)
    def input(self, *args):
        temp = str(args[0]).split('=')
        element = self.query_element(temp[0], temp[1])
        element.click()
        element.clear()
        element.send_keys(args[1])

    def click(self, *args):
        temp = str(args[0]).split('=')
        element = self.query_element(temp[0], temp[1])
        element.click()

    def close(self):
        self.driver.quit()'''


class KeyWords:

    # module_name_ = os.path.basename(__file__).split('.')[0]
    # logger = Logger.get_logger(module_name_)
    def __init__(self):
        self.driver = Driver.get_driver()
        module_name_ = os.path.basename(__file__).split('.')[0]
        self.logger = Logger.get_logger(module_name_)
    # __driver = UIDriver.get_driver()

    def find_element_by_visiblewait(self, locator, timeout=15, poll_frequency=0.5):
        """
        通过显示等待找元素
        :param locator: 元素定位器
        :param timeout:超时时间
        :param poll_frequency:寻找频率
        :return:找到返回元素，没有返回None
        """
        try:
            wait = WebDriverWait(self.driver, timeout, poll_frequency)
            element = wait.until(ec.visibility_of_element_located((getattr(By, locator[0]), locator[1])))
        except:
            element = None
        return element

    def is_presence_element(self, locator, timeout=30, poll_frequency=0.5):
        """
        判断元素是否存在
        :param locator: 元素定位器
        :param timeout:超时时间
        :param poll_frequency:寻找频率
        :return:存在返回True，不存在返回False
        """
        element = self.find_element_by_visiblewait(locator, timeout=timeout, poll_frequency=poll_frequency)
        if element:
            return True
        else:
            return False

    def open(self, url):
        try:
            self.driver.get(url)
        except Exception as e:
            self.logger.error(f'driver或{url}异常'+ str(e))

    # def query_element(self, loc):
    #     element = None
    #     try:
    #         element = self.driver.find_element(getattr(By, loc[0]), loc[1])
    #     except Exception as e:
    #         self.logger.error(f'元素定位方式{loc[0]}或{loc[1]}异常'+ str(e))
    #     return element

    def query_element(self, loc):
        element = None
        try:
            element = self.find_element_by_visiblewait(loc)
        except Exception as e:
            self.logger.error(f'元素定位方式{loc[0]}或{loc[1]}异常'+ str(e))
        return element

    def input(self, loc, value):
        element = self.query_element(loc)
        if element is not None:
            try:
                element.clear()
                element.send_keys(value)
            except Exception as e:
                self.logger.error(f'输入文本{value}异常' + str(e))

    def input_textarea(self, loc, value):
        """
        向文本域输入内容
        :param loc: 文本域元素定位信息
        :param value: 要输入的值
        :return: None
        """
        element = self.query_element(loc)
        if element is not None:
            element.click()
            element.send_keys(value)

    def click(self, loc):
        element = self.query_element(loc)
        if element is not None:
            element.click()

    def quit(self):
        self.driver.quit()

    def select_random_option(self, loc):
        """
        从下拉框中随机选择一个option
        :return:
        """
        import random
        element = self.query_element(loc)
        if element != None:
            random_index = random.randint(0, len(Select(element).options))
            Select(element).select_by_index(random_index)

    def select_option(self, loc, text):
        """
        根据select的option值进行选择
        :param loc:
        :param text:
        :return:
        """
        element = self.query_element(loc)
        if element != None:
            Select(element).select_by_visible_text(text)

    def find_element_by_attr(self, element_attr):
        """
        找到元素对象并返回
        :param element_attr: 元素属性
        :return: 元素对象
        """

        return self.driver.find_element(getattr(By, element_attr[0]), element_attr[1])

    def is_element_present(self, loc):
        """
        判断某个元素是否存在
        :param loc: 元素的属性的元组形式
        :return: 是否存在的标识
        """
        try:
            element = self.query_element(loc)
            return True
        except Exception as e:
            return False

    # def switch_iframe_and_execute(self, iloc, keymethod, *args):
    #     iframe = self.find_element_by_visiblewait(iloc)
    #     self.driver.switch_to.frame(iframe)
    #     print(args)
    #     getattr(self,keymethod)(*args)
        
        # self.click()
        # self.driver.switch_to.parent_frame()

    def switch_iframe_and_execute(self, iloc, eloc,):
        # iframe = self.find_element_by_visiblewait(iloc)
        iframe = self.driver.find_element_by_css_selector(iloc[1])
        self.driver.switch_to.frame(iframe)
        # getattr(self, keymethod)(eloc)

        self.click(eloc)
        # self.driver.find_element_by_css_selector('button.btn:nth-child(5)')
        # self.driver.switch_to.parent_frame()

    def switch_iframe(self, loc):
        iframe = self.find_element_by_visiblewait(loc)
        # iframe = self.driver.find_element_by_css_selector('iframe#testIframe')
        self.driver.switch_to.frame(iframe)
        import time
        time.sleep(2)

    def switch_back(self):
        """
        退出iframe, 返回主层
        :return:
        """
        self.driver.switch_to.parent_frame()

    def get_screenshot(self):
        try:
            # pic_dir = Config().pic_dir
            # Utils.make_dir(pic_dir)
            # pic = os.path.join(pic_dir, case_id) if case_id else pic_dir
            # Utils.make_dir(pic)
            # print(PIC_PATH)
            filename = os.path.join(PIC_PATH,
                                    "{}.png".format(datetime.strftime(datetime.now(), "%Y-%m-%d_%H-%M-%S")))
            self.driver.get_screenshot_as_file(filename)
            return repr(filename)
        except Exception as e:
            self.logger.error('截图失败' + e.__str__())

    def get_ele_txt(self,loc):
        text = None
        try:
            ele = self.find_element_by_visiblewait(loc)
            text = ele.text
        except Exception as e:
            self.logger.error('获取文本失败'+ e.__str__())
        return text

if __name__ == '__main__':
    r = KeyWords().get_screenshot()
    print(r)
    pass
